package com.yuesystem.service.impl;


import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.yuesystem.common.BaseContext;
import com.yuesystem.entity.Like;
import com.yuesystem.mapper.LikeMapper;
import com.yuesystem.service.LikeService;
import java.util.List;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;



/**
 * 点赞接口实现类.
 */
@Slf4j
@Service
public class LikeServiceImpl extends ServiceImpl<LikeMapper, Like> implements LikeService {
  
  /**
   * 判断当前用户是否点赞过该帖子.
   *
   * @param blogId 帖子id
   * @return 是否赞过
   */
  @Override
  public Boolean judge(Long blogId) {
    // 获取当前用户id
    Long userId = BaseContext.getCurrentId();
    
    // 根据userId 和 blogId 去查询数据库
    LambdaQueryWrapper<Like> queryWrapper = new LambdaQueryWrapper<>();
    queryWrapper.eq(Like::getBlogId, blogId).eq(Like::getUserId, userId);
    Like one = this.getOne(queryWrapper);
    return one != null; // 用户未收藏过该贴子，返回false,再次点击应该是添加点赞
    // 用户已收藏该帖子，返回true，再次点击应该是取消点赞
  }
  
  
  /**
   * 用户点赞帖子.
   *
   * @param blogId 帖子id
   */
  @Override
  public void add(Long blogId) {
    // 获取当前用户id
    Long userId = BaseContext.getCurrentId();
    
    Like like = new Like();
    like.setUserId(userId);
    like.setBlogId(blogId);
    this.save(like);
  }
  
  /**
   * 用户取消点赞帖子.
   *
   * @param blogId 帖子id
   */
  @Override
  public void cancel(Long blogId) {
    // 获取当前用户id
    Long userId = BaseContext.getCurrentId();
    
    LambdaQueryWrapper<Like> queryWrapper = new LambdaQueryWrapper<>();
    queryWrapper.eq(Like::getUserId, userId).eq(Like::getBlogId, blogId);
    this.remove(queryWrapper);
  }
  
  /**
   * 根据传来的帖子id,统计并返回该帖子的点赞数量.
   *
   * @param blogId 帖子id
   * @return 点赞数量
   */
  @Override
  public Long getLikeCount(Long blogId) {
    LambdaQueryWrapper<Like> queryWrapper = new LambdaQueryWrapper<>();
    queryWrapper.eq(Like::getBlogId, blogId);
    Long counts = this.count(queryWrapper);
    return counts;
  }
  
  /**
   * 根据用户id删除他的所有点赞记录.
   *
   * @param userId 用户id
   */
  @Override
  public void deleteById(Long userId) {
    LambdaQueryWrapper<Like> queryWrapper = new LambdaQueryWrapper<>();
    queryWrapper.eq(Like::getUserId, userId);
    this.remove(queryWrapper);
  }
  
  /**
   * 根据blog的id删除所有点赞.
   *
   * @param listBlog 博客列表
   */
  @Override
  public void deleteByBlog(List<Long> listBlog) {
    LambdaQueryWrapper<Like> queryWrapper = new LambdaQueryWrapper<>();
    queryWrapper.in(listBlog.size() != 0, Like::getBlogId, listBlog);
    this.remove(queryWrapper);
  }
  
  
}
